package com.chuanqi.admin.controller; 

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chuanqi.admin.domain.OperationLog;
import com.chuanqi.admin.domain.PermittedRecordModel;
import com.chuanqi.admin.domain.User;
import com.chuanqi.admin.domain.UserRole;
import com.chuanqi.admin.qp.UserQp;

import com.chuanqi.admin.service.OperationLogService;
import com.chuanqi.admin.service.PermittedItemResourceIdService;
import com.chuanqi.admin.service.UserRoleService;
import com.chuanqi.admin.service.UserService;
import com.chuanqi.common.utils.SplitIdsStr2ListUtils;

@Controller
@RequestMapping("/authc/user")
public class AdminUserController {

    @Autowired
    private UserService userService;

    @Autowired
    private UserRoleService userRoleService;    
    
    @Autowired
    private OperationLogService operationLogService;
    
    @Autowired
    private PermittedItemResourceIdService permittedItemResourceIdService;

    @RequiresPermissions("user:view")	
    @RequestMapping(value = "/list", method = RequestMethod.GET)	
	public String showFirstPageGet(Model model) {			
		final long rowCount = userService.getAllUsersTotalCount();				
		List<User> users = userService.getFirstPageUsers();			
		int pageIndex = 1;
		int pageSize = 10;
		
		String sortName = "USERNAME";
		String sortOrder = "ASC";
	    
	    long totalPages = rowCount / pageSize;
	    long mod = rowCount % pageSize;
	    if (mod > 0) {
	    	totalPages++;
	    }
		
	    if( rowCount - (pageIndex-1)*pageSize > 0 ){
	    	model.addAttribute("current", pageIndex);    	   	
	    	model.addAttribute("pageSize", pageSize);	
			
	    	model.addAttribute("sortName", sortName);
			model.addAttribute("sortOrder", sortOrder);	
			
			model.addAttribute("totalPages", totalPages);
			model.addAttribute("total", rowCount);				    
		    
			model.addAttribute("from", pageIndex);
		    model.addAttribute("to", pageSize);
		    
		    model.addAttribute("users", users);  
	    }     			
		 
		return "authc/user/list";  
	}    
    
    @RequiresPermissions("user:view")	
    @RequestMapping(value = "/list", method = RequestMethod.POST)
	public String queryPagePost(
			@RequestParam(value = "pageIndex", defaultValue = "1") int pageIndex,
			@RequestParam(value = "pageSize", defaultValue = "10") int pageSize,    		  
    		HttpServletRequest request,
    		Model model) {			
		
		String sortName = request.getParameter("sortName"); 		
		String sortOrder = request.getParameter("sortOrder");	
				
		String username = request.getParameter("username");
		
		if( StringUtils.isBlank(sortName) || StringUtils.isBlank(sortOrder) ){
			sortName = "USERNAME";
			sortOrder = "ASC";
		}
		
		long offset = pageIndex > 0 ? (pageIndex - 1) * pageSize : 0;
		UserQp qp = new UserQp();
		qp.setOffset(offset);		
		qp.setPageSize(pageSize);	
		
		qp.setUsername(username);			
		qp.setSortName(sortName);
		qp.setSortOrder(sortOrder);			
		
		final long rowCount = userService.getCountByQueryBean(qp);				
		List<User> users = userService.getByQueryBean(qp);			
		
	    long totalPages = rowCount / pageSize;
	    long mod = rowCount % pageSize;
	    if (mod > 0) {
	    	totalPages++;
	    }    
	    
	    long from = (pageIndex - 1) * pageSize + 1;
		long to = 0l;
		
		if(pageIndex<totalPages){			
			to = pageIndex * pageSize;
		}else{
			to = rowCount;
		}			
		
	    if( rowCount - (pageIndex-1)*pageSize > 0 ){
	    	model.addAttribute("current", pageIndex);    	   	
	    	model.addAttribute("pageSize", pageSize);	
			
			model.addAttribute("sortName", sortName);
			model.addAttribute("sortOrder", sortOrder);			
			
			model.addAttribute("totalPages", totalPages);
			model.addAttribute("total", rowCount);				    
		    
			model.addAttribute("from", from);
		    model.addAttribute("to", to);
		    
		    model.addAttribute("users", users);  
	    }     			
	   
	    List<PermittedRecordModel> permittedRecordModels = permittedItemResourceIdService.getPermittedItemResourceIdByUserIdForTest(7L);        	
    	List<Long> permittedItemIds = new ArrayList<Long>();
    	for(PermittedRecordModel entity : permittedRecordModels){
    		permittedItemIds.add(entity.getRecordId());   
    		System.out.println(entity.getRecordId());
    	}	    
    	
		return "authc/user/list";  
	}
    
	@RequestMapping(value = "/checkLoginName", method = RequestMethod.GET)
	@ResponseBody
	public String checkLoginName(@RequestParam("username") String username) {
		if(userService.findByUsername(username)!=null){
			return "false";
    	}else {
    		return "true";
		}		 
	}
	
	@RequestMapping(value = "/checkLoginNameById/{id}", method = RequestMethod.GET)
	@ResponseBody
	public String checkLoginNameById(@PathVariable("id") Long id, @RequestParam("username") String username) {
		if(userService.findByUsername(username)!=null && ! username.equals(userService.getOneById(id).getUsername())){
			return "false";
    	}else {
    		return "true";
		}		 
	}
	
	@RequiresPermissions("user:create")
    @RequestMapping(value = "/create", method = RequestMethod.GET)
    public String createGet(Model model) {    	
    	User user = new User();    	
        model.addAttribute("user", user);
        model.addAttribute("action", "create");    	
        
        return "authc/user/form";
    }

    @RequiresPermissions("user:create")
    @RequestMapping(value = "/create", method = RequestMethod.POST)
    public String create(@Valid @ModelAttribute("user") User user, BindingResult bindingResult, RedirectAttributes redirectAttributes, Model model) {
    	if (bindingResult.hasErrors()) {    		
    		model.addAttribute("action", "create");        	
        	return "authc/user/form";
        }   	
    	
    	userService.createUser(user);
    	redirectAttributes.addFlashAttribute("message", "新增管理员成功!");
        return "redirect:/authc/user/list";    	       
    }    

    @RequiresPermissions("user:update")
    @RequestMapping(value = "/update/{id}", method = RequestMethod.GET)
    public String showUpdateForm(@PathVariable("id") Long id, Model model) {
    	User user = userService.getOneById(id);
    	model.addAttribute("user", user);
        model.addAttribute("action", "update");
        return "authc/user/form";
    }

    @RequiresPermissions("user:update")
    @RequestMapping(value = "/update", method = RequestMethod.POST)
    public String update(@Valid @ModelAttribute("user") User user, BindingResult result, RedirectAttributes redirectAttributes, HttpServletRequest request, Model model) {
    	if (result.hasErrors()) {    		
    		model.addAttribute("action", "update");
			return "authc/user/form";
		}    	
    	
		if (user != null) {					
			userService.updateUser(user);
	        redirectAttributes.addFlashAttribute("message", "修改管理员成功!");
		} 
    	
        return "redirect:/authc/user/list";
    }    
    
    @RequiresPermissions("user:update")
    @RequestMapping(value="/updatePassword/{userId}", method=RequestMethod.POST)
	public String updatePasswordPost(@PathVariable Long userId, HttpServletRequest request, RedirectAttributes redirectAttributes){
    	String newPassword = request.getParameter("password");
    	
    	userService.changePassword(userId, newPassword);
    	
		redirectAttributes.addFlashAttribute("message", "更新密码成功！");
        return "redirect:/authc/user/list"; 
	}
    
    @RequiresPermissions("user:update")
    @RequestMapping(value="/updateAccount/{userId}", method=RequestMethod.POST)
	public String updateAccountPost(@PathVariable Long userId, HttpServletRequest request, RedirectAttributes redirectAttributes){
    	String status = request.getParameter("status");
    	if(status.equals("true")){
    		userService.updateAccount(userId, true); 
    	}else{
    		userService.updateAccount(userId, false); 
    	}   	
    	
		redirectAttributes.addFlashAttribute("message", "更新账户状态成功！");
        return "redirect:/authc/user/list"; 
	}        
    
    
    @RequiresPermissions("user:view")
    @RequestMapping(value="/showRolesByUserId/{userId}", method=RequestMethod.GET)
	public String showRolesByUserIdGet(@PathVariable("userId") Long userId,  Model model){    	
    	model.addAttribute("username", userService.getOneById(userId).getUsername());
    	model.addAttribute("userId", userId);
    	return "authc/user/roleCheckboxTree";
	}    
    
    @RequiresPermissions("role:update")
    @RequestMapping(value = "/updateUserRole", method = RequestMethod.POST)
    public String updateRoleResourcePost(HttpServletRequest request) {
    	Long userId = Long.parseLong( request.getParameter("userId") );
    	String idsStr = request.getParameter("resourceIds");    	
    	userRoleService.deleteRbyUR(userId);    	
    	List<Long> ids = SplitIdsStr2ListUtils.splitIdsStr2List(idsStr);
    	for(int i=0;i<ids.size();i++){
    		Long rId = ids.get(i);
    		UserRole rr = new UserRole();
    		rr.setUserId(userId);
    		rr.setRoleId(rId);    		
    		userRoleService.insertRbyUR(rr);
    	}
		
        return "redirect:/authc/user/list";
    }    
    
    private boolean isSupervisor(Long id) {
		return id == 1;
	}
    
    @RequiresPermissions("user:delete")
    @RequestMapping(value="/delete/{userId}", method=RequestMethod.GET)
	public String deleteById(@PathVariable("userId") Long userId, RedirectAttributes redirectAttributes){
    	if (isSupervisor(userId)) {			
    		redirectAttributes.addFlashAttribute("message", "不能删除超级管理员用户！");
            return "redirect:/authc/user/list"; 
		}
    	
    	userService.deleteUser(userId);
						
		String opPermission = "user:delete";				
		Date now = new Date();			
		SimpleDateFormat simpleDateformat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");			
		Timestamp opTime = Timestamp.valueOf(simpleDateformat.format(now));			
		
		OperationLog opLog = new OperationLog(userId, opPermission, opTime);
		operationLogService.insert(opLog);
		
		redirectAttributes.addFlashAttribute("message", "删除管理员成功！");
        return "redirect:/authc/user/list"; 
	}    
}
